<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus'
import axios from 'axios'

// 搜索条件
const searchForm = ref({
  deptName: '',
  status: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 部门数据列表
const deptData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const isEditing = ref(false)
const formData = ref({
  id: '',
  name: '',
  status: 1
})

// 获取认证token
const getAuthToken = () => {
  return localStorage.getItem('token') || sessionStorage.getItem('token')
}

// 创建axios实例，添加认证头
const apiClient = axios.create()
apiClient.interceptors.request.use(config => {
  const token = getAuthToken()
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 获取部门列表（支持分页和搜索）
const fetchDeptList = async () => {
  console.log('开始获取部门列表，页码:', currentPage.value, '每页大小:', pageSize.value)
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.value.deptName) {
      params.name = searchForm.value.deptName
      console.log('搜索条件 - 部门名称:', params.name)
    }
    
    if (searchForm.value.status) {
        params.status = searchForm.value.status === 'normal' ? 1 : 0
        console.log('搜索条件 - 状态:', params.status)
      }
      
      console.log('完整请求参数:', params)
      
      // 调用部门列表查询接口
      const response = await apiClient.get('/api/depts', { params })
      
      console.log('API响应:', response.data)
      
      if (response.data && response.data.code === 1) {
      // 检查响应数据结构
      console.log('响应数据结构:', {
        code: response.data.code,
        dataExists: !!response.data.data,
        rowsExists: Array.isArray(response.data.data?.rows),
        rowsLength: response.data.data?.rows?.length || 0,
        totalExists: typeof response.data.data?.total === 'number'
      })
      
      // 处理返回的数据
      deptData.value = response.data.data.rows.map((item, index) => ({
        ...item,
        displayId: (currentPage.value - 1) * pageSize.value + index + 1,
        // 转换状态格式以匹配前端显示需要
        status: item.status === 1 ? 'normal' : 'disabled',
        // 转换时间格式
        lastModifiedTime: formatDateTime(item.updateTime || item.createTime)
      }))
      
      // 更新总数
      total.value = response.data.data.total
      console.log('数据加载成功，共', total.value, '条记录，当前页', deptData.value.length, '条')
    } else {
      console.error('API返回错误码:', response.data?.code, '消息:', response.data?.msg)
      ElMessage.error('获取部门列表失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取部门列表异常:', error)
    
    if (error.response) {
      console.error('HTTP错误状态:', error.response.status)
      console.error('错误响应数据:', error.response.data)
    } else if (error.request) {
      console.error('请求已发出但未收到响应:', error.request)
    } else {
      console.error('请求配置错误:', error.message)
    }
    
    if (error.response && error.response.status === 401) {
      ElMessage.error('未授权访问，请重新登录')
    } else {
      ElMessage.error('获取部门列表失败，请稍后重试')
    }
  } finally {
    console.log('数据加载完成')
    loading.value = false
  }
}

// 分页变化处理
const handleSizeChange = (newSize) => {
  console.log('分页大小变化:', newSize)
  pageSize.value = newSize
  currentPage.value = 1 // 重置到第一页
  fetchDeptList()
}

const handleCurrentChange = (newPage) => {
  console.log('当前页码变化:', newPage)
  currentPage.value = newPage
  fetchDeptList()
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1 // 搜索后重置到第一页
  fetchDeptList()
}

// 清空搜索
const handleReset = () => {
  searchForm.value = {
    deptName: '',
    status: ''
  }
  fetchDeptList()
}

// 打开添加部门对话框
const handleAdd = () => {
  isEditing.value = false
  formData.value = {
    id: '',
    name: '',
    status: 1
  }
  dialogVisible.value = true
}

// 打开编辑部门对话框
const handleEdit = async (id) => {
    try {
      // 根据ID查询部门详情
      const response = await apiClient.get(`/api/depts/${id}`)
      
      if (response.data && response.data.code === 1) {
      const deptInfo = response.data.data
      isEditing.value = true
      formData.value = {
        id: deptInfo.id,
        name: deptInfo.name,
        status: deptInfo.status
      }
      dialogVisible.value = true
    } else {
      ElMessage.error('获取部门详情失败: ' + (response.data?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('查询部门详情错误:', error)
    
    if (error.response && error.response.status === 401) {
      ElMessage.error('未授权访问，请重新登录')
    } else {
      ElMessage.error('获取部门详情失败，请稍后重试')
    }
  }
}

// 保存部门信息（添加或修改）
const handleSave = async () => {
  // 表单验证
  if (!formData.value.name.trim()) {
    ElMessage.warning('部门名称不能为空')
    return
  }
  
  try {
    if (isEditing.value) {
        // 修改部门
        const response = await apiClient.put('/api/depts', formData.value)
        
        if (response.data && response.data.code === 1) {
        ElMessage.success('修改部门成功')
        dialogVisible.value = false
        fetchDeptList() // 重新加载数据
      } else {
        ElMessage.error('修改部门失败: ' + (response.data?.msg || '未知错误'))
      }
    } else {
        // 添加部门
        const response = await apiClient.post('/api/depts', formData.value)
        
        if (response.data && response.data.code === 1) {
        ElMessage.success('添加部门成功')
        dialogVisible.value = false
        fetchDeptList() // 重新加载数据
      } else {
        ElMessage.error('添加部门失败: ' + (response.data?.msg || '未知错误'))
      }
    }
  } catch (error) {
    console.error(isEditing.value ? '修改部门错误' : '添加部门错误', error)
    
    if (error.response && error.response.status === 401) {
      ElMessage.error('未授权访问，请重新登录')
    } else {
      ElMessage.error(isEditing.value ? '修改部门失败' : '添加部门失败')
    }
  }
}

// 删除部门
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这个部门吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
        // 调用删除接口
        const response = await apiClient.delete(`/api/depts/${id}`)
        
        if (response.data && response.data.code === 1) {
        ElMessage.success('删除成功')
        
        // 检查当前页是否还有数据，如果没有且不是第一页，则回到上一页
        if (deptData.value.length === 1 && currentPage.value > 1) {
          currentPage.value--
        }
        
        fetchDeptList() // 重新加载数据
      } else {
        ElMessage.error('删除失败: ' + (response.data?.msg || '未知错误'))
      }
    } catch (error) {
      console.error('删除部门错误:', error)
      
      if (error.response && error.response.status === 401) {
        ElMessage.error('未授权访问，请重新登录')
      } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 状态显示文本
const getStatusText = (status) => {
  return status === 'normal' ? '正常' : '停用'
}

// 获取状态样式类名
const getStatusClass = (status) => {
  return status === 'normal' ? 'text-success' : 'text-danger'
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  if (isNaN(date.getTime())) return dateString
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 初始化时加载数据
onMounted(() => {
  console.log('组件挂载，开始初始化数据')
  // 立即执行fetchDeptList以加载初始数据
  fetchDeptList()
})
</script>

<template>
  <div class="dept-management">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="部门名称：">
          <el-input v-model="searchForm.deptName" placeholder="请输入部门名称" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="searchForm.status" placeholder="请选择" style="width: 150px;">
            <el-option label="正常" value="normal" />
            <el-option label="停用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item class="form-buttons">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">清空</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 添加部门按钮单独一行 -->
    <div class="add-button-area">
      <el-button type="primary" @click="handleAdd">添加部门</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="deptData" style="width: 100%; margin-top: 20px;">
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">
          {{ scope.row.displayId }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="部门名称" align="center">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" align="center">
        <template #default="scope">
          <span :class="getStatusClass(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template #default="scope">
          {{ scope.row.createTime ? formatDateTime(scope.row.createTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="最后修改时间" align="center">
        <template #default="scope">
          {{ scope.row.lastModifiedTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" text @click="handleEdit(scope.row.id)">修改</el-button>
            <el-button type="danger" text @click="handleDelete(scope.row.id)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination" style="margin-top: 20px; text-align: center;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, prev, pager, next, jumper, sizes"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 部门编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '修改部门' : '添加部门'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form label-position="top" :model="formData" style="padding: 20px 0;">
        <el-form-item label="部门名称：">
          <el-input v-model="formData.name" placeholder="请输入部门名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.dept-management {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  box-sizing: border-box;
  min-height: 600px;
}

/* 确保在布局容器中正确显示 */
:deep(.el-main) {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: 100vh;
  overflow-y: auto;
}

.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
}

.search-form {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.form-buttons {
  margin-left: auto;
}

.add-button-area {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

/* 确保输入框和选择器样式一致 */
.el-input__wrapper,
.el-select__wrapper {
  border-radius: 4px;
}

/* 调整表单项目间距 */
.el-form-item {
  margin-right: 20px;
}

/* 调整表格和分页的容器 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.pagination {
  margin-top: 16px;
  text-align: center;
}

/* 调整表格样式 */
.el-table__header th,
.el-table__body td {
  padding: 12px 10px;
  text-align: center;
}

/* 操作列宽度调整 */
.el-table-column--fixed-right {
  width: 120px;
}

/* 操作按钮容器样式 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  flex-wrap: nowrap;
  white-space: nowrap;
}

/* 操作按钮样式 */
.action-buttons .el-button--text {
  padding: 8px 12px;
  font-size: 14px;
  white-space: nowrap;
}

/* 确保按钮不换行 */
.action-buttons .el-button {
  flex-shrink: 0;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

/* 表头样式设置 - 蓝色背景 */
.el-table__header-wrapper {
  background-color: #409EFF;
}

/* 表头单元格样式 - 蓝色背景 */
.el-table__header th {
  background-color: #409EFF !important;
  color: white !important;
  font-weight: bold;
  padding: 12px 15px;
  line-height: 1.6;
  border: 1px solid #dcdfe6;
  border-right: none;
}

/* 修复最后一个表头单元格的右边框 */
.el-table__header th:last-child {
  border-right: 1px solid #dcdfe6;
}

/* 确保固定列的表头也有相同的样式 */
.el-table__header th.is-hidden-column,
.el-table__header th.is-right-fixed-column {
  background-color: #409EFF !important;
  color: white !important;
  border-right: 1px solid #dcdfe6;
}

/* 移除默认的表头hover效果 */
.el-table__header th:hover {
  background-color: #409EFF !important;
}

/* 表格内容单元格样式 */
.el-table__body td {
  padding: 16px 15px;
  line-height: 1.6;
}

/* 确保操作按钮间距适当 */
.el-table .el-button--text {
  padding: 5px 10px;
}

/* 状态文字样式 */
.text-success {
  color: #67c23a;
}

.text-danger {
  color: #f56c6c;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-area {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-area .el-button {
    margin-top: 10px;
    width: 100%;
  }
}
</style>
